#include "CurlRequestUtil.h"
#include <gio/gio.h>

void sendGetRequest(const char* url, size_t (*fn)(void*,size_t,size_t,void*))
{
    CURL *curl = curl_easy_init();
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fn);
        CURLcode res = curl_easy_perform(curl);
        if (res!=CURLE_OK)
        {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }
        curl_easy_cleanup(curl);
    }
}

void sendPostRequest(const char* url, const char* param, size_t (*fn)(void*,size_t,size_t,void*))
{
    CURL *curl = curl_easy_init();
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_URL, url);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, fn);
        // 给post请求设置参数
        curl_easy_setopt(curl, CURLOPT_POSTFIELDS, param);

        CURLcode res = curl_easy_perform(curl);
        if (res!=CURLE_OK)
        {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
        }
        curl_easy_cleanup(curl);
    }
}


/**
 * url 是线上资源路径，就是http请求
 * savleFilePath 本地保存路径
 */
int downloadRes(char *url,char * savleFilePath){
    // 判断本地文件是否存在，如果不存在需要先创建
    gboolean exist = g_file_test(savleFilePath,G_FILE_TEST_EXISTS);
    if(!exist)
    {
        // 先创建本地文件
        GFile *file = g_file_new_for_path(savleFilePath);
        if(!g_file_create(file,G_FILE_CREATE_NONE,NULL,NULL))
        {
            printf("文件创建失败!\n");
            return -1;
        }
    }

    //要保持的文件路径
    FILE *saveFile =  fopen(savleFilePath,"wb");
    //初始化
    CURL *curl = curl_easy_init();
    if (curl)
    {
        //设置相关参数  url  存数据的文件
        curl_easy_setopt(curl,CURLOPT_URL,url);   
        //设置访问资源之间存放文件
        curl_easy_setopt(curl,CURLOPT_FILE,saveFile);  
        
        //发请求
         CURLcode res = curl_easy_perform(curl);

        //判断是否发送成功
        if (res!=CURLE_OK)
        {
            fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
            return -1;
        }
        curl_easy_cleanup(curl);
    }
    
    return 0;
}

